<template>
  <div class="article-management">
    <div class="toolbar">
      <div>
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>新建文章
        </el-button>
      </div>
      <div class="toolbar-info">
        <el-tag v-if="isAdmin" type="success">管理员视图：显示所有文章</el-tag>
        <el-tag v-else type="info">个人视图：仅显示您创建的文章</el-tag>
      </div>
    </div>

    <el-table :data="articles" style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="categoryName" label="分类" width="120" />
      <el-table-column v-if="isAdmin" prop="nickname" label="作者" width="120" />
      <el-table-column prop="viewCount" label="浏览量" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          <el-button type="info" link @click="handleViewComments(row)">查看评论</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建文章' : '编辑文章'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
          />
        </el-form-item>
        <div v-if="dialogType === 'edit'" class="form-tip">
          <el-alert
            title="提示：文章编辑后将重新进入待审核状态，需要管理员审核通过后才能显示。"
            type="warning"
            :closable="false"
          />
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="commentDialogVisible"
      title="文章评论"
      width="600px"
    >
      <div v-if="articleComments.length > 0">
        <div v-for="comment in articleComments" :key="comment.id" class="comment-item">
          <div class="comment-header">
            <span class="comment-author">{{ comment.nickname }}</span>
            <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
        </div>
      </div>
      <div v-else>
        暂无评论
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { article, category, comment } from '@/api'

const loading = ref(false)
const articles = ref([])
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const isAdmin = ref(localStorage.getItem('role') === 'ADMIN')
const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref(null)
const commentDialogVisible = ref(false)
const articleComments = ref([])
const currentArticleId = ref(null)

const form = ref({
  title: '',
  categoryId: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '已发布'
    case 2:
      return '已拒绝'
    default:
      return '未知'
  }
}

const loadArticles = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      status: -1
    }
    const res = await article.manageList(params)
    articles.value = res.records
    total.value = res.total
  } catch (error) {
    console.error(error)
    ElMessage.error('加载文章列表失败')
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    const res = await category.list()
    categories.value = res
  } catch (error) {
    console.error(error)
    ElMessage.error('加载分类列表失败')
  }
}

const handleViewComments = async (row) => {
  try {
    const res = await comment.getByArticle(row.id)
    articleComments.value = res
    commentDialogVisible.value = true
  } catch (error) {
    console.error(error)
    ElMessage.error('加载评论失败')
  }
}

const handleCreate = () => {
  dialogType.value = 'create'
  form.value = {
    title: '',
    categoryId: '',
    content: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  currentArticleId.value = row.id
  form.value = {
    id: row.id,
    title: row.title,
    categoryId: row.categoryId,
    content: row.content,
    userId: row.userId
  }
  console.log('编辑文章数据:', form.value);
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这篇文章吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await article.delete(row.id)
      ElMessage.success('删除成功')
      loadArticles()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'create') {
          await article.create(form.value)
          ElMessage.success('创建成功')
        } else {
          console.log('提交更新数据:', form.value);
          if (currentArticleId.value) {
            // 确保ID正确传递，但不传递status字段，让后端控制
            const { status, ...updateData } = {
              ...form.value,
              id: currentArticleId.value
            };
            console.log('最终提交的更新数据(不含status):', updateData);
            await article.update(currentArticleId.value, updateData)
            ElMessage.success('更新成功，文章已提交重新审核')
          } else {
            ElMessage.error('文章ID丢失，无法更新')
          }
        }
        dialogVisible.value = false
        loadArticles()
      } catch (error) {
        console.error(error)
        ElMessage.error(dialogType.value === 'create' ? '创建失败' : '更新失败')
      }
    }
  })
}

const handleSizeChange = (val) => {
  console.log('修改每页显示条数:', val);
  pageSize.value = val;
  currentPage.value = 1; // 切换每页条数时，重置为第一页
  loadArticles();
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadArticles()
}

const getStatusType = (status) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

onMounted(() => {
  loadArticles()
  loadCategories()
})
</script>

<style scoped>
.article-management {
  background: white;
  padding: 20px;
  border-radius: 4px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-info {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.comment-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.comment-header {
  margin-bottom: 5px;
}

.comment-author {
  font-weight: bold;
  margin-right: 10px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  color: #333;
}

.form-tip {
  margin: 10px 0;
}
</style> 